<template>
    <view class="pg-center">
        <view class="cont mb-safe">
            <view class="w-700">
                <wd-notice-bar text="盒子展示商品, 点击可直接购买" :scrollable="false" prefix="goods" color="#34D19D" background-color="#f0f9eb" />
            </view>
            <view class="w-700 h-auto fl-ro-cen ju-bet flex-wrap">
                <goods-item v-for="item in goodsItemList" :goodsItem="item" @handle_click="goods_onclick(item)"></goods-item>
            </view>
            <view class="w-700 m-20-0">
                <wd-notice-bar text="便捷功能" prefix="thumb-up" :scrollable="false" type="info" />
            </view>
            <free-paper :paperItem="paper.goodsDto" @handle_click="paper_onclick()"></free-paper>
            <view class="w-700 h-auto fl-ro-cen ju-bet gap-20">
                <view class="w-340 h-210 fl-ro-cen ju-bet bg-teal-400 rd-10 overflow-hidden p-20" @click="charge">
                    <text class="fs-50 font-bold text-white">快捷充电</text>
                    <image class="w-260" src="../../../static/image/闪电排序.svg" mode="widthFix"></image>
                </view>
                <view class="w-340 h-210 fl-ro-cen ju-bet bg-orange-400 rd-10 overflow-hidden p-20" @click="shop">
                    <text class="fs-50 font-bold text-white w-100">精品商城</text>
                    <image class="w-130 mr-10" src="../../../static/image/商城.svg" mode="widthFix"></image>
                </view>
            </view>
        </view>
        <!-- tabbar -->
        <wd-tabbar v-model="tabbar" @change="tab_change" active-color="#0055ff" inactive-color="#7d7e80" fixed bordered safeAreaInsetBottom placeholder>
            <wd-tabbar-item name="index" title="首页" icon="home"></wd-tabbar-item>
            <!-- <wd-tabbar-item name="fine-mall" title="商城" icon="goods"></wd-tabbar-item> -->
            <wd-tabbar-item name="user" title="我的" icon="user"></wd-tabbar-item>
        </wd-tabbar>
    </view>
</template>

<script setup>
    import { onShow, onLoad } from '@dcloudio/uni-app';
    import { callWithErrorHandling, ref } from 'vue';
    import { api_machine_getDtoFull } from '@/api/machine.js';
    import { api_machineOrder_new, api_machineOrder_wxPay, api_machineOrder_wxPayCallBack } from '@/api/machineOrder.js';
    import { useCurrentUserStore } from '@/store/currentUser.js';
    import { scanCodeGetSN } from '@/utils/scanCodeGetSN';

    const tabbar = ref(''); //标签的索引值
    const goodsItemList = ref([]); //机器商品列表
    const paper = ref({}); //免费纸巾

    onShow(() => {
        //由于wd-tabbar的bug，进入页面立马手动更新tabbar，实现图标换色
        tabbar.value = 'index';
        console.log(`进入了${tabbar.value}页`);
    });

    onLoad(async () => {
        //加载当前机器的详细数据
        try {
            let res1 = await api_machine_getDtoFull({ sn: uni.getStorageSync('user').machineSn });
            uni.setStorageSync('user', { ...uni.getStorageSync('user'), machineId: res1.data.id });
            paper.value = res1.data.machineOption.goodsList[0]; //第一个是免费纸巾
            console.log('烦死付红树林', paper.value.goodsDto);
            goodsItemList.value = res1.data.machineOption.goodsList.slice(1); //商品列表
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none'
            });
        }
    });

    //点击商品
    const goods_onclick = (item) => {
        console.log(item);
        uni.showModal({
            title: '是否购买该商品',
            success: async (res) => {
                if (res.confirm) {
                    console.log(`购买了${item.goodsDto.name}`);
                    //访问购买商品接口
                    try {
                        let res = await api_machineOrder_new({
                            machineId: uni.getStorageSync('user').machineId,
                            mogId: item.id
                        });

                        if (res.code === 200) {
                            //成功就拿订单id去换支付参数
                            // 在这里try catch
                            try {
                                let resw = await api_machineOrder_wxPay({
                                    createId: res.data.createId,
                                    id: res.data.id
                                });
                                if (resw.code === 200) {
                                    console.log(resw);
                                    //调用微信官方支付接口弹出付款界面,输入密码扣款
                                    wx.requestPayment({
                                        timeStamp: resw.data.timeStamp, //时间戳
                                        nonceStr: resw.data.nonceStr, //随机字符串
                                        package: resw.data.package, //prepay_id
                                        signType: resw.data.signType, //签名算法MD5
                                        paySign: resw.data.paySign, //签名
                                        success: async (res3) => {
                                            if (res3.errMsg == 'requestPayment:ok') {
                                                console.log('支付成功', res);
                                                try {
                                                    await api_machineOrder_wxPayCallBack({
                                                        orderNo: res.data.orderNo
                                                    });
                                                    uni.showToast({
                                                        title: '支付成功！',
                                                        icon: 'none',
                                                        duration: 2000
                                                    });
                                                } catch (error) {
                                                    uni.showToast({
                                                        title: error,
                                                        icon: 'none',
                                                        duration: 2000
                                                    });
                                                }
                                            } else {
                                                console.log('支付失败');
                                            }
                                        },
                                        fail(res) {
                                            console.log('支付失败', res);
                                        }
                                    });
                                }
                            } catch (error) {
                                console.log(error);
                                uni.showToast({
                                    title: error.msg,
                                    icon: 'none',
                                    duration: 2000
                                });
                            }
                        } else {
                            //其他情况就结束
                            return;
                        }
                    } catch (error) {
                        uni.showToast({
                            title: error.msg,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            }
        });
    };

    //点击纸巾
    const paper_onclick = async () => {
        console.log('点击了纸巾');
        try {
            let res = await api_machineOrder_new({
                machineId: uni.getStorageSync('user').machineId,
                mogId: paper.value.id
            });
            if (res.code === 200) {
                //成功就拿订单id去换支付参数
                // 在这里try catch
                try {
                    let resw = await api_machineOrder_wxPay({
                        createId: res.data.createId,
                        id: res.data.id
                    });
                    if (resw.code === 200) {
                        console.log(resw);
                        //调用微信官方支付接口弹出付款界面,输入密码扣款
                        wx.requestPayment({
                            timeStamp: resw.data.timeStamp, //时间戳
                            nonceStr: resw.data.nonceStr, //随机字符串
                            package: resw.data.package, //prepay_id
                            signType: resw.data.signType, //签名算法MD5
                            paySign: resw.data.paySign, //签名
                            success: async (res3) => {
                                if (res3.errMsg == 'requestPayment:ok') {
                                    console.log('支付成功', res);
                                    try {
                                        await api_machineOrder_wxPayCallBack({
                                            orderNo: res.data.orderNo
                                        });
                                        uni.showToast({
                                            title: '支付成功！',
                                            icon: 'none',
                                            duration: 2000
                                        });
                                    } catch (error) {
                                        uni.showToast({
                                            title: error,
                                            icon: 'none',
                                            duration: 2000
                                        });
                                    }
                                } else {
                                    console.log('支付失败');
                                }
                            },
                            fail(res) {
                                console.log('支付失败', res);
                            }
                        });
                    }
                } catch (error) {
                    console.log(error);
                    uni.showToast({
                        title: error.msg,
                        icon: 'none',
                        duration: 2000
                    });
                }
            } else {
                //其他情况就结束
                return;
            }
        } catch (error) {
            uni.showToast({
                title: error.msg,
                icon: 'none',
                duration: 2000
            });
        }
    };

    //点击快捷充电
    const charge = () => {
        console.log('点击了充电');
        uni.navigateTo({
            url: '/pages/custom/index/charge-select/charge-select'
        });
    };

    //点击扫码换机
    // const scan_click = async () => {
    //     console.log('点击了扫码换机');
    //     // 调起条码扫描
    //     try {
    //         let sn = await scanCodeGetSN();
    //         console.log('sn:', sn);
    //         uni.setStorageSync('user', { ...uni.getStorageSync('user'), machineSn: sn });
    //     } catch (error) {
    //         uni.showToast({
    //             title: '识别失败',
    //             icon: 'none'
    //         });
    //     }
    // };

    //点击精品商城
    const shop = () => {
        console.log('点击了精品商城');
        uni.navigateTo({
            url: '/pages/custom/fine-mall/fine-mall'
        });
    };

    //点击tabbar
    const tab_change = ({ value }) => {
        uni.switchTab({
            url: `/pages/custom/${value}/${value}`
        });
    };
</script>

<style lang="scss" scoped>
    :deep(.search) {
        background-color: #f8f8f8;
    }
</style>
